<template>
    <el-dialog v-model="localVisible" width="1200px" class="ba-operate-dialog order-info-dialog"
        :close-on-click-modal="false" :destroy-on-close="true" @update:model-value="updateVisible">
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                订单详情
            </div>
        </template>
        <el-scrollbar v-loading="loading" class="ba-table-form-scrollbar">
            <div class="ba-operate-form order-info-content">
                <!-- 订单信息 -->
                <div class="info-section">
                    <h3 class="section-title">订单信息</h3>
                    <el-descriptions border :column="2">
                        <el-descriptions-item label="订单号">{{ orderData.order_no || '-' }}</el-descriptions-item>
                        <el-descriptions-item label="姓名">{{ orderData.user_name || '-' }}</el-descriptions-item>
                        <el-descriptions-item label="下单用户">
                            {{ orderData.user.nickname || '-' }}(用户ID: {{ orderData.user_id || '-' }})
                        </el-descriptions-item>
                        <el-descriptions-item label="电话">{{ orderData.user_mobile || '-' }}</el-descriptions-item>
                        <el-descriptions-item label="下单时间">{{ formatTime(orderData.createtime) }}</el-descriptions-item>
                        <el-descriptions-item label="地址">{{ orderData.user_address || '-' }}</el-descriptions-item>
                        <el-descriptions-item label="支付方式">{{ orderData.pay_type || '-' }}</el-descriptions-item>
                        <el-descriptions-item label="备注">{{ orderData.remark || '-' }}</el-descriptions-item>
                        <el-descriptions-item label="支付时间">{{ formatTime(orderData.pay_time) || '-'
                            }}</el-descriptions-item>
                    </el-descriptions>
                </div>

                <!-- 订单状态 -->
                <div class="info-section">
                    <h3 class="section-title">订单状态</h3>
                    <el-descriptions border :column="1">
                        <el-descriptions-item label="订单状态" :label-width="100">
                            <span class="order-status" :class="`status-${orderData.status}`">
                                {{ getStatusText(orderData.status) }}
                            </span>
                        </el-descriptions-item>
                        <el-descriptions-item label="发货时间" :label-width="100" v-if="orderData.status >= 31">
                            <span v-if="orderData.status >= 31">
                                {{ formatTime(orderData.delivery_time) }}
                            </span>
                        </el-descriptions-item>
                        <el-descriptions-item label="收货时间" :label-width="100" v-if="orderData.status >= 32">
                            <span v-if="orderData.status >= 32">
                                {{ formatTime(orderData.receive_time) }}
                            </span>

                        </el-descriptions-item>
                        <el-descriptions-item label="操作" :label-width="100" v-if="orderData.status === 30">
                            <el-button type="primary" @click="handleDelivery">物流发货</el-button>
                        </el-descriptions-item>
                        <el-descriptions-item label="操作" :label-width="100" v-if="orderData.status === 31">
                            <el-button type="primary" @click="confirmReceive">确认收货</el-button>
                        </el-descriptions-item>
                    </el-descriptions>
                </div>

                <!-- 物流信息 -->
                <div class="info-section" v-if="orderData.wuliu_no || orderData.wuliu_gs">
                    <h3 class="section-title">物流信息</h3>
                    <el-descriptions border :column="1">
                        <el-descriptions-item label="发货时间" :label-width="100">
                            {{ formatTime(orderData.delivery_time) || '-' }}
                        </el-descriptions-item>
                        <el-descriptions-item label="物流公司" :label-width="100">
                            {{ getExpressName(orderData.wuliu_gs) }}
                        </el-descriptions-item>
                        <el-descriptions-item label="物流单号" :label-width="100">
                            {{ orderData.wuliu_no || '-' }}
                        </el-descriptions-item>
                    </el-descriptions>
                    <el-button type="primary" style="margin-top: 10px" @click="checkExpress">物流查询</el-button>
                </div>
                <!-- 商品信息 -->
                <div class="info-section">
                    <h3 class="section-title">商品信息</h3>
                    <el-table table-layout="fixed" :data="orderData.text || []" style="width: 100%;" border>
                        <el-table-column label="主图" align="center">
                            <template #default="scope">
                                <img v-if="scope.row.goods_img" :src="fullUrl(scope.row.goods_img)" alt="商品图片"
                                    style="width: 28px; height: 28px;" />
                            </template>
                        </el-table-column>
                        <el-table-column label="商品名称" align="center">
                            <template #default="scope">
                                {{ scope.row.goods_name || '-' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="购买规格" align="center">
                            <template #default="scope">
                                {{ scope.row.spec_name || '-' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="数量" align="center">
                            <template #default="scope">
                                {{ scope.row.num || '-' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="单价" align="center">
                            <template #default="scope">
                                {{ scope.row.price || '-' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="总价" align="center">
                            <template #default="scope">
                                {{ scope.row.price * scope.row.num || '-' }}
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- 总计信息 -->
                    <div
                        style="margin-top: 10px; font-weight: bold; gap: 10px; display: flex; justify-content: flex-end;">
                        <span>会员:￥{{ orderData.discount_price || '-' }}</span>
                        <span>SVIP:￥{{ orderData.svip_price || '-' }}</span>
                        <span>积分:￥{{ orderData.score_price || '-' }}</span>
                        <span>优惠券:￥{{ orderData.coupon_price || '-' }}</span>
                        <span>平台手续费:￥{{ orderData.platform_hand_fees || '-' }}</span>
                    </div>
                    <div
                        style="margin-top: 10px; font-weight: bold;color: #333; gap: 10px; display: flex; justify-content: flex-end;">
                        <span>商品总价:￥{{ orderData.total_price || '-' }}</span>
                        <span>实付金额:￥{{ orderData.pay_price || '-' }}</span>
                    </div>
                </div>

                <!-- 操作按钮区域 -->
                <div class="order-actions">
                    <el-button @click="handlePrint">打印</el-button>
                </div>
            </div>
        </el-scrollbar>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">关闭</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 物流发货弹窗 -->
    <el-dialog v-model="deliveryVisible" title="商品发货" width="600px" :close-on-click-modal="false">
        <el-form :model="deliveryForm" label-width="100px">
            <el-form-item label="物流公司" required>
                <el-select v-model="deliveryForm.expressCompany" placeholder="请选择物流公司" style="width: 100%" filterable>
                    <el-option v-for="item in expressList" :key="item.id || item.value" :label="item.name || item.label"
                        :value="item.id || item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="物流单号" required>
                <el-input v-model="deliveryForm.expressNumber" placeholder="请输入物流单号"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="deliveryVisible = false">取消</el-button>
            <el-button type="primary" :loading="deliveryLoading" @click="submitDelivery">确认发货</el-button>
        </template>
    </el-dialog>

    <!-- 物流查询弹窗 -->
    <el-dialog v-model="expressVisible" title="物流信息查询" width="600px" :close-on-click-modal="false">
        <div class="express-info">
            <el-descriptions border :column="1" :label-width="100">
                <el-descriptions-item label="物流公司">
                    {{ expressInfo.company || '-' }}
                </el-descriptions-item>
                <el-descriptions-item label="物流单号">
                    {{ expressInfo.number || '-' }}
                </el-descriptions-item>
            </el-descriptions>

            <div class="express-timeline" v-if="expressData.length > 0">
                <h4 style="margin: 16px 0; color: #606266;">物流动态</h4>
                <el-scrollbar style="max-height: 400px;">
                    <div v-for="(item, index) in expressData" :key="index" class="express-item"
                        :class="{ 'express-item-first': index === 0 }">
                        <div class="express-time">{{ item.time }}</div>
                        <div class="express-content">{{ item.content }}</div>
                    </div>
                </el-scrollbar>
            </div>

            <div v-else class="no-data">
                <el-empty description="暂无物流信息"></el-empty>
            </div>
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, inject, watch, onMounted } from 'vue'
import { useConfig } from '/@/stores/config'
import { fullUrl } from '/@/utils/common'
import createAxios from '/@/utils/axios'
import { ElMessage } from 'element-plus'

interface OrderData {
    order_no: string
    username?: string
    nickname?: string
    user_id?: string | number
    phone?: string
    createtime?: string | number
    address?: string
    pay_type?: string
    remark?: string
    pay_time?: string | number
    status?: number
    receipt_time?: string | number
    express_name?: string
    express_no?: string
    ship_time?: string | number
    [key: string]: any
}

const props = defineProps<{
    visible: boolean
    data?: OrderData
}>()

const config = useConfig()
const loading = ref(false)

// 本地可见性状态
const localVisible = ref(false)

// 监听props.visible变化，更新本地状态
watch(() => props.visible, (newVal) => {
    localVisible.value = newVal
}, { immediate: true })

// 更新可见性事件
const updateVisible = (value: boolean) => {
    localVisible.value = value
    emit('update:visible', value)
}

const emit = defineEmits<{
    'update:visible': [visible: boolean]
    'refresh-data': []
}>()

// 订单数据
const orderData = computed(() => props.data || {}) as any
console.log("orderData", orderData.value)

// 物流公司列表
const expressList = ref<any[]>([])

// 是否已经获取过物流公司列表的标志
const hasFetchedExpressList = ref(false)

// 获取物流公司列表
const fetchExpressList = async () => {
    // 如果已经获取过，不再重复请求
    if (hasFetchedExpressList.value) {
        return
    }

    try {
        const response = await createAxios({
            url: '/expressquery/getExpressList',
            method: 'get',
            // 添加一个唯一的时间戳参数，避免重复请求被取消
            params: { _t: Date.now() }
        }, {
            // 禁用重复请求取消功能
            cancelDuplicateRequest: false,
            loading: true,
            showErrorMessage: true
        })

        if (response && response.data && Array.isArray(response.data)) {
            expressList.value = response.data
            hasFetchedExpressList.value = true
        }
    } catch (error) {
        console.error('获取物流公司数据失败:', error)
    }
}

// 根据物流公司ID获取物流公司名称
const getExpressName = (expressId: string | number) => {
    if (!expressId) return expressId || '-'

    const express = expressList.value.find(item =>
        String(item.id) === String(expressId) || String(item.value) === String(expressId)
    )

    return express ? express.name || express.label : expressId
}

// 状态文本映射
const getStatusText = (status?: number) => {
    if (!status) return ''
    const statusMap: Record<number, string> = {
        10: '待支付',
        20: '已取消',
        30: '待发货',
        31: '待收货',
        32: '已完成',
        33: '退货退款',
        34: '退货中',
        35: '售后完成',
        40: '退款中',
        41: '退款完成',
        42: '拒绝退款'
    }
    return statusMap[status] || '未知状态'
}

// 时间格式化
const formatTime = (time: any) => {
    if (!time || time === '0000-00-00 00:00:00' || time === '0') {
        return ''
    }

    try {
        const timeStr = String(time).trim();
        let date: Date;

        if (/^\d{10}$/.test(timeStr)) {
            date = new Date(Number(timeStr) * 1000);
        } else if (/^\d{13}$/.test(timeStr)) {
            date = new Date(Number(timeStr));
        } else {
            date = new Date(time);
        }

        if (isNaN(date.getTime())) {
            return String(time);
        }

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hour = String(date.getHours()).padStart(2, '0');
        const minute = String(date.getMinutes()).padStart(2, '0');
        const second = String(date.getSeconds()).padStart(2, '0');

        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    } catch (error) {
        return String(time);
    }
}

// 处理关闭
const handleClose = () => {
    localVisible.value = false
    emit('update:visible', false)
}

// 处理打印
const handlePrint = () => {
    console.log('打印订单:', orderData.value)
    // 这里可以实现打印功能
    alert('打印功能待实现')
}

// 物流查询相关状态
const expressVisible = ref(false)
const expressLoading = ref(false)
const expressData = ref<any[]>([])
const expressInfo = ref<{ company: string; number: string }>({ company: '', number: '' })

// 物流发货相关状态
const deliveryVisible = ref(false)
const deliveryLoading = ref(false)
const deliveryForm = ref({
    expressCompany: '',
    expressNumber: ''
})

// 打开物流发货弹窗
const handleDelivery = () => {
    deliveryForm.value = {
        expressCompany: '',
        expressNumber: ''
    }
    deliveryVisible.value = true
}

// 提交物流发货信息
const submitDelivery = async () => {
    if (!deliveryForm.value.expressCompany || !deliveryForm.value.expressNumber) {
        ElMessage.warning('请填写完整的物流信息')
        return
    }

    deliveryLoading.value = true
    try {
        const response = await createAxios({
            url: `/goodsorder/send?ids=${orderData.value.id}`,
            method: 'post',
            data: {
                row: {
                    wuliu_gs_text: getExpressName(deliveryForm.value.expressCompany),
                    wuliu_gs: deliveryForm.value.expressCompany,
                    wuliu_no: deliveryForm.value.expressNumber
                }
            }
        }, {
            loading: true,
            showErrorMessage: true
        })

        if (response && response.code === 0) {
            ElMessage.success('发货成功')
            deliveryVisible.value = false
            // 刷新订单数据，可以通过父组件传递的刷新方法实现
            emit('refresh-data')
        }
    } catch (error) {
        console.error('物流发货失败:', error)
    } finally {
        deliveryLoading.value = false
    }
}

// 确认收货
const confirmReceive = async () => {
    try {
        const response = await createAxios({
            url: '/goodsorder/receive',
            method: 'post',
            data: {
                ids: orderData.value.id
            }
        }, {
            loading: true,
            showErrorMessage: true
        })

        if (response && response.code === 0) {
            ElMessage.success('确认收货成功')
            // 刷新订单数据
            emit('refresh-data')
        }
    } catch (error) {
        console.error('确认收货失败:', error)
    }
}

// 物流查询
const checkExpress = async () => {
    if (!orderData.value.wuliu_gs || !orderData.value.wuliu_no) {
        console.warn('缺少物流信息')
        return
    }

    expressInfo.value = {
        company: getExpressName(orderData.value.wuliu_gs),
        number: orderData.value.wuliu_no
    }

    expressLoading.value = true
    try {
        // 调用物流查询接口
        const response = await createAxios({
            url: '/goodsorder/express',
            method: 'post',
            params: {
                ids: orderData.value.id,
            }
        }, {
            loading: true,
            showErrorMessage: true
        })
        if (response && response.code === 0 && response.data) {
            expressData.value = response.data
        }
        expressVisible.value = true
    } catch (error) {
        console.error('物流查询失败:', error)
    } finally {
        expressLoading.value = false
    }
}

// 组件挂载时获取物流公司数据
onMounted(() => {
    fetchExpressList()
})
</script>

<style scoped lang="scss">
.order-info-dialog {
    .ba-table-form-scrollbar {
        max-height: 60vh;
    }

    .ba-operate-form {
        padding: 0;
    }

    .order-info-content {
        .info-section {
            margin-bottom: 24px;
            padding: 16px;
            background-color: #fafafa;
            border-radius: 4px;
            border: 1px solid #e4e7ed;

            .section-title {
                font-size: 16px;
                font-weight: 500;
                margin-bottom: 16px;
                color: #303133;
                border-left: 3px solid #409eff;
                padding-left: 10px;
            }
        }

        .el-descriptions {
            margin-bottom: 0;

            .el-descriptions__row {
                margin-bottom: 0;
            }

            .el-descriptions__label {
                font-weight: 500;
                color: #606266;
                background-color: #fafafa;
            }

            .el-descriptions__content {
                color: #303133;
            }
        }

        .order-status {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-10 {
            background-color: #e6f7ff;
            color: #1890ff;
        }

        .status-20 {
            background-color: #f5f5f5;
            color: #909399;
        }

        .status-30,
        .status-31 {
            background-color: #fff7e6;
            color: #fa8c16;
        }

        .status-32 {
            background-color: #f0f9ff;
            color: #00b42a;
        }

        .status-33,
        .status-34,
        .status-40 {
            background-color: #fff0f6;
            color: #f5222d;
        }

        .status-35,
        .status-41,
        .status-42 {
            background-color: #f6ffed;
            color: #52c41a;
        }

        .order-actions {
            display: flex;
            gap: 10px;
            // margin-top: 20px;
            padding: 16px;
            background-color: #fff;
            border-radius: 4px;
            justify-content: flex-start;
        }
    }

    :deep(.el-dialog__footer) {
        padding: 10px 20px 20px;
        text-align: flex-end;
    }

    .dialog-footer {
        display: flex;
        justify-content: flex-end;
    }
}

// 物流查询弹窗样式
.express-info {
    .el-descriptions {
        margin-bottom: 16px;
    }

    .express-timeline {
        .express-item {
            position: relative;
            padding-left: 24px;
            padding-bottom: 16px;
            min-height: 60px;

            &::before {
                content: '';
                position: absolute;
                left: 6px;
                top: 20px;
                bottom: 0;
                width: 1px;
                background-color: #e4e7ed;
            }

            &::after {
                content: '';
                position: absolute;
                left: 2px;
                top: 16px;
                width: 9px;
                height: 9px;
                border-radius: 50%;
                background-color: #dcdfe6;
            }

            &.express-item-first {
                &::after {
                    background-color: #409eff;
                    border: 2px solid #ecf5ff;
                }

                .express-time {
                    color: #409eff;
                    font-weight: 500;
                }

                .express-content {
                    color: #303133;
                    font-weight: 500;
                }
            }

            &:last-child {
                &::before {
                    display: none;
                }
            }
        }

        .express-time {
            font-size: 14px;
            color: #606266;
            margin-bottom: 8px;
        }

        .express-content {
            font-size: 14px;
            color: #606266;
            line-height: 1.5;
        }
    }

    .no-data {
        padding: 40px 0;
    }
}
</style>
